package dao

import (
	"context"
	"core/models/entity"
	"core/repo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type UserDao struct {
	repo *repo.Manager
}

/*
*
根据Uid查找用户
*/
func (d *UserDao) FindUserByUid(ctx context.Context, uid string) (*entity.User, error) {
	table := d.repo.Mongo.Db.Collection("user")
	singleResult := table.FindOne(ctx, bson.D{
		{"uid", uid},
	})
	user := new(entity.User)
	err := singleResult.Decode(user)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, nil
		}
		return nil, err
	}
	return user, nil
}

/*
*
插入用户
*/
func (d *UserDao) InsertUser(ctx context.Context, user *entity.User) error {
	table := d.repo.Mongo.Db.Collection("user")
	_, err := table.InsertOne(ctx, user)
	if err != nil {
		return err
	}
	return nil
}

/*
*
更新用户位置信息
*/
func (d *UserDao) UpdateUserAddressByUid(ctx context.Context, user *entity.User) error {
	table := d.repo.Mongo.Db.Collection("user")
	filter := bson.M{"uid": user.Uid}
	_, err := table.UpdateOne(ctx, filter, bson.M{
		"$set": bson.M{
			"address":  user.Address,
			"location": user.Location,
		},
	})
	return err
}

/*
*
初始化
*/
func NewUserDao(m *repo.Manager) *UserDao {
	return &UserDao{
		repo: m,
	}
}
